/*
 * @Author: your name
 * @Date: 2020-04-10 17:00:18
 * @LastEditTime: 2020-05-03 23:04:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cellProject\src\modules\Front\data\api\Cell\model.js
 */
// 树形转扁平
// 把 level, Id, Name, Pid 这些想要获取的键值名作为参数带进去,给每个层级增加一个level
function flatten (data, keys, level = 0) {
  return data.reduce((arr, x) => [
    ...arr,
    keys.reduce((o, k) => (o[k] = x[k] === 0 ? x[k] : x[k] ? x[k] : '', o), { level }),
    ...flatten(x.children || [], keys, level + 1)
  ], [])
}
// flatten(arr, ['Id', 'Name', 'Pid', 'id'])

export const getTreeList = {
  request (params) {
    return params
  },
  response (data) {
    const dataArr = data.data

    function getPosNodePaths (obj) {
      // 最大层数/行数
      var maxRowNum = 0
      // 最大列数
      var maxColNum = 0
      // 单元格宽度
      var cellW = 80
      // 单元格高度
      var cellH = 60
      // 水平间距/列距
      var hSpace = 20
      // 垂直间距/行距
      var vSpace = 50
      // 画布宽度
      var paperW = 0
      // 画布高度
      var paperH = 0
      const requireKeys = [
        'id', 'name', 'pid', 'positionX', 'positionY',
        'inTopPort', 'outLeftPort', 'outRightPort', 'outBottomPort'
      ]
      const nodes = []
      const paths = []
      Object.assign(obj, {
        positionX: 5,
        positionY: 30,
        inTopPort: {
          id: `${obj.id}_in_1`,
          isConnected: true,
          content: '入口'
        },
        outLeftPort: {
          id: `${obj.id}_out_l`,
          isConnected: true,
          content: '左出口'
        },
        outRightPort: {
          id: `${obj.id}_out_r`,
          isConnected: true,
          content: '右出口'
        },
        outBottomPort: {
          id: `${obj.id}_out_b`,
          isConnected: true,
          content: '底出口'
        }
      })
      nodes.push(
        obj,
        ...flatten(obj.children, requireKeys, obj.level + 1 || 1)
      )
      // 计算添置坐标
      calcXY(obj, 1, 'positionX', 'positionY', nodes, paths)
      // 父节点重置坐标
      calcParentXY(obj, 'positionX', nodes)

      // 获取子集方法
      function getChildren (obj, targetArr) {
        var childrenArr = []
        for (var i = 0; i < targetArr.length; i++) {
          if (targetArr[i].pid == obj.id) {
            childrenArr.push(targetArr[i])
          }
        }
        return childrenArr
      }
      // 递归添加坐标和路径
      function calcXY (obj, level, xKey, yKey, targetArr, targetPaths) {
        level++
        var childrenArr = getChildren(obj, targetArr)
        for (var i = 0; i < childrenArr.length; i++) {
          //
          childrenArr[i].inTopPort = {
            id: childrenArr[i].id + '_in_t',
            isConnected: true,
            content: '入口'
          }
          childrenArr[i].outLeftPort = {
            id: childrenArr[i].id + '_out_l',
            content: '左出口'
          }
          childrenArr[i].outRightPort = {
            id: childrenArr[i].id + '_out_r',
            content: '右出口'
          }
          childrenArr[i].outBottomPort = {
            id: childrenArr[i].id + '_out_b',
            content: '底出口'
          }
          // 路径
          targetPaths.push(
            {
              dotted: false,
              ptype: 'L',
              startPort: `${obj.id}_out_b`,
              endPort: childrenArr[i].inTopPort.id
            }
          )
          if (i == 0) {
            childrenArr[i][xKey] = obj[xKey]
          } else {
            var offsetX = 0
            var childrenArr2 = getChildren(childrenArr[i - 1], targetArr)
            if (childrenArr2.length > 0) {
              offsetX = childrenArr2[childrenArr2.length - 1][xKey]
            } else {
              offsetX = childrenArr[i - 1][xKey]
            }
            childrenArr[i][xKey] = offsetX + (cellW + hSpace)
          }
          childrenArr[i][yKey] += (cellH + vSpace) * level
          obj[xKey] = childrenArr[i][xKey]
          calcXY(childrenArr[i], level, xKey, yKey, targetArr, targetPaths)
        }
      }
      // 父节点坐标修正
      function calcParentXY (obj, xKey, targetArr) {
        var childrenArr = getChildren(obj, targetArr)
        for (var i = 0; i < childrenArr.length; i++) {
          calcParentXY(childrenArr[i], xKey, targetArr)
        }
        if (childrenArr.length > 0) {
          if (childrenArr.length % 2 == 0) {
            obj[xKey] = (childrenArr[0][xKey] + childrenArr[childrenArr.length - 1][xKey]) / 2
          } else {
            obj[xKey] = childrenArr[Math.floor(childrenArr.length / 2)][xKey]
          }
        }
      }
      // 统计不重复的父节点总个数
      var _rowSet = new Set()
      for (var i = 0; i < nodes.length; i++) {
        _rowSet.add(nodes[i].pid)
      }
      //
      maxRowNum = _rowSet.size
      // 节点总数-（父节点总数-1）; 1--根节点没有父节点，排除
      maxColNum = nodes.length - (_rowSet.size - 1)
      paperW = maxColNum * (cellW + hSpace)
      paperH = maxRowNum * (cellH + vSpace)
      return {
        nodes,
        paths,
        paperW,
        paperH
      }
    }

    var nodes = []; var paths = []; var paperWs = []; var paperHs = []
    var temp = {}
    dataArr.forEach((obj, index) => {
      temp[index] = getPosNodePaths(obj)
      if (index > 0) {
        temp[index].nodes.map(item => {
          item.positionX = item.positionX + temp[index - 1].paperW
        })
      }
      nodes = nodes.concat(temp[index].nodes)
      paths = paths.concat(temp[index].paths)
      paperWs.push(temp[index].paperW)
      paperHs.push(temp[index].paperH)
    })
    console.log(temp[0].nodes)
    var _index = Math.floor(Math.random() + dataArr.length) - 1
    if (_index > 0) {
      // 随机选树形两个路径点
      paths.push({
        dotted: true,
        ptype: 'Q',
        startPort: temp[_index - 1].nodes[Math.floor(Math.random() + temp[_index - 1].nodes.length) - 1].outBottomPort.id,
        endPort: temp[_index].nodes[Math.floor(Math.random() + temp[_index].nodes.length) - 1].outBottomPort.id
      })
    }

    return { nodes, paths, paperWs, paperHs }
  }
}
